﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNet.Utilities;
//using KingRoad.EPM.InvestmeEntity;
using System.Xml;
using KingRoad.EPM.Common.Configuration;
using DotNet.Service;
using DotNet.Model.MyEntity;

namespace KingRoad.EPM.Web.Controllers
{
    [AuthorizeType(NeedLogin = false)]
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        OperateXml operateXml = new OperateXml();

        public ActionResult Index()
        {
            string newXml = operateXml.ReadXml();
            string[] tempList = newXml.Split(';');
            ViewBag.Copyright = tempList[0];
            ViewBag.Href = tempList[1];
            ViewBag.CompanyName = tempList[2];
            ViewBag.Phone = tempList[3];
            ViewBag.VersionNumber = tempList[5];
            ViewBag.SysTitle = tempList[6];

            return View();
        }

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ValidateUser(string userName, string pwd, string ReturnUrl)
        {
            string type = Request.Params["subtype"];
            string checkInput = string.Empty;
            try
            {
                string returnStatusCode = string.Empty;
                string returnStatusMessage = string.Empty;
                // 登录验证
                BaseUserInfo userInfo = ServiceManager.Instance.UserService.LogOn(userName, pwd, true, true, out returnStatusCode, out returnStatusMessage);
                // 登录结果
                if (returnStatusCode.Equals(StatusCode.OK.ToString()))
                {
                    //userInfo.RealName = (ServiceManager.Instance.UserService.GetDTByUserName(userInfo.UserName) ?? new Base_User()).RoleName;
                    IList<Base_Duty> list = new OrganizeService().GetDutysByUserName(userName);
                    List<Base_OrgAndDuty> modellist = ServiceManager.Instance.OrganizeService.GetDutysAndOrgsByUserId(int.Parse(UserService.CurrUserInfo.Id)) as List<Base_OrgAndDuty>;
                    //若有岗位，则进行岗位赋值
                    if (modellist != null && modellist.Count > 0)
                    {
                        userInfo.RoleName = modellist.First().OrgCode;
                    }
                    if (list != null && String.IsNullOrEmpty(Request["Duty"]) && list.Count > 1)
                    {
                        //若有多个岗位而没有选择岗位的话，则提示
                        TempData["msg"] = "提示信息：登录失败，请选择岗位。";
                        return RedirectToAction("Index", KingRoad.EPM.Common.Configuration.Settings.Instance.defaultpage);
                    }
                    else if (!String.IsNullOrEmpty(Request["Duty"]))
                    {
                        userInfo.WorkgroupId = int.Parse(Request["DutyID"]);
                        userInfo.WorkgroupCode = Request["Duty"];
                        userInfo.WorkgroupFullName = Request["DutyName"];
                    }
                    else
                    {
                        //默认取第一个为岗位
                        if (list != null && list.Count > 0)
                        {
                            userInfo.WorkgroupCode = list.First().Code;
                            userInfo.WorkgroupFullName = list.First().Name;
                            userInfo.WorkgroupId = list.First().ID;
                        }
                    }
                    userInfo.CompanyFullName = userInfo.DepartmentFullName;
                    userInfo.Themes = "0";
                    UserService.CurrUserInfo = userInfo;
                    if (!String.IsNullOrEmpty(ReturnUrl))
                    {
                        return Redirect(ReturnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    if (type == "uLogin")
                        returnStatusMessage = "非法U盾！";
                    //登录失败
                    TempData["msg"] = returnStatusMessage;
                    return RedirectToAction("Index", "Login");
                }
            }
            catch(Exception e)
            {
                //登录失败
                if (type == "uLogin")
                    TempData["msg"] = "非法U盾！";
                else
                    TempData["msg"] = "提示信息：登录失败，请检查你的用户名和密码是否输入有误。";
                return RedirectToAction("Index", "Login");
            }
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public ActionResult LogOff()
        {
            try
            {
                new UserService().Logout();
            }
            catch (Exception ex)
            {

                throw;
            }
            //登出报错已修复
            return RedirectToAction("Index", "Login");
        }


        public ActionResult GetDutyByUsername(string userName)
        {
            IList<Base_Duty> list = new OrganizeService().GetDutysByUserName(userName);
            string statuCode = string.Empty;
            if (list != null)
                statuCode = "200";
            return Json(new KingRoad.EPM.Web.ViewModels.CallbackStatus
            {
                statusCode = statuCode,
                data = list
            });
        }
    }
}
